import React, { useState, useEffect } from 'react';
import { List, Input, Card, Spin, Empty } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import axios from 'axios';
import Fuse from 'fuse.js';

const { Search } = Input;

function Home() {
  const [scripts, setScripts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [filteredScripts, setFilteredScripts] = useState([]);

  useEffect(() => {
    // 获取剧本列表
    const fetchScripts = async () => {
      try {
        const response = await axios.get('http://localhost:5000/api/scripts');
        setScripts(response.data);
        setFilteredScripts(response.data);
        setLoading(false);
      } catch (error) {
        console.error('Error fetching scripts:', error);
        setLoading(false);
      }
    };

    fetchScripts();
  }, []);

  const handleSearch = (value) => {
    if (!value) {
      setFilteredScripts(scripts);
      return;
    }

    const fuse = new Fuse(scripts, {
      keys: ['name'], // 搜索字段
      threshold: 0.3, // 匹配阈值
    });

    const results = fuse.search(value).map(result => result.item);
    setFilteredScripts(results);
  };

  return (
    <div>
      <Search
        placeholder="搜索剧本名称"
        allowClear
        enterButton={<SearchOutlined />}
        size="large"
        onSearch={handleSearch}
        style={{ marginBottom: 20 }}
      />

      {loading ? (
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Spin size="large" />
        </div>
      ) : filteredScripts.length > 0 ? (
        <List
          grid={{ gutter: 16, column: 3 }}
          dataSource={filteredScripts}
          renderItem={script => (
            <List.Item>
              <Card
                title={script.name}
                hoverable
                onClick={() => window.location.href = `/script/${script._id}`}
              >
                <p>ID: {script._id}</p>
                <p>剧本简介: {script.description || '暂无简介'}</p>
              </Card>
            </List.Item>
          )}
        />
      ) : (
        <Empty description="没有找到匹配的剧本" />
      )}
    </div>
  );
}

export default Home;